package com.yss.reportworld.service.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.constant.RequestDataHelper;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.easyexecl.EasyExeclUtil;
import com.yss.common.core.utils.easyexecl.ExcelListener;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.utils.DictUtils;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.util.TableInfoUtil;
import com.yss.system.api.domain.SysDictData;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.yss.reportworld.service.IDemandBugInfoService;
import com.yss.reportworld.mapper.DemandBugInfoMapper;
import com.yss.reportworld.domain.DemandBugInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 需求bug信息Service业务层处理
 *
 * @author yss
 * @date 2023-03-27
 */
@Slf4j
@Service
public class DemandBugInfoServiceImpl extends ServiceImpl<DemandBugInfoMapper, DemandBugInfo> implements IDemandBugInfoService {
    /**
     * 查询需求bug信息列表
     *
     * @param demandBugInfo 需求bug信息
     * @return 需求bug信息
     */
    @Override
    public List<DemandBugInfo> selectDemandBugInfoList(DemandBugInfo demandBugInfo) {
        try {
            TableInfoUtil.handleTableVersion(demandBugInfo.getHisVersion()); // 替换表名
            QueryWrapper<DemandBugInfo> wrapper = new QueryWrapper();
            wrapper.orderByDesc("CREATE_TIME");
            if (StringUtils.isNotEmpty(demandBugInfo.getDemandBugNum())) {
                wrapper.eq("DEMAND_BUG_NUM", demandBugInfo.getDemandBugNum());
            }
            if (StringUtils.isNotEmpty(demandBugInfo.getDescription())) {
                wrapper.like("DESCRIPTION", demandBugInfo.getDescription());
            }
            if (null != demandBugInfo.getDemandBugType()) {
                wrapper.eq("DEMAND_BUG_TYPE", demandBugInfo.getDemandBugType());
            }
            if (null != demandBugInfo.getDemandBugFsource()) {
                wrapper.eq("DEMAND_BUG_FSOURCE", demandBugInfo.getDemandBugFsource());
            }
            if (StringUtils.isNotEmpty(demandBugInfo.getParams())) {
                if (null != demandBugInfo.getParams().get("beginTime") && StringUtils.isNotEmpty(demandBugInfo.getParams().get("beginTime").toString())) {
                    wrapper.ge("DEMAND_BUG_DATE", demandBugInfo.getParams().get("beginTime"));
                }
                if (null != demandBugInfo.getParams().get("endTime") && StringUtils.isNotEmpty(demandBugInfo.getParams().get("endTime").toString())) {
                    wrapper.le("DEMAND_BUG_DATE", demandBugInfo.getParams().get("endTime"));
                }
            }
            if (StringUtils.isNotEmpty(demandBugInfo.getVersion())) {
                wrapper.eq("VERSION", demandBugInfo.getVersion());
            }
            // 导出的时候选择了数据，按照选择的数据
            if (StringUtils.isNotEmpty(demandBugInfo.getIds())) {
                List<String> list = JSONArray.parseArray(demandBugInfo.getIds(), String.class);
                if (StringUtils.isNotEmpty(list)) {
                    wrapper.in("ID", list);
                }
            }
            return this.list(wrapper);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    @Override
    public DemandBugInfo getDemandBugInfo(DemandBugInfo demandBugInfo) {
        try {
            TableInfoUtil.handleTableVersion(demandBugInfo.getHisVersion()); // 替换表名
            return this.getById(demandBugInfo.getId());
        } catch (Exception ex) {
            throw new BusinessException("查询需求BUG信息失败" + ex.getMessage());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    @Override
    public void insertDemandBugInfo(DemandBugInfo demandBugInfo) {
        try {
            TableInfoUtil.handleTableVersion(demandBugInfo.getHisVersion()); // 替换表名
            if (!this.checkDemandBugInfoUnique(demandBugInfo)) {
                throw new BusinessException("版本【" + demandBugInfo.getVersion() + "】需求编号【" + demandBugInfo.getDemandBugNum() + "】已存在");
            }
            demandBugInfo.setCreateBy(SecurityUtils.getUsername());
            demandBugInfo.setCreateTime(new Date());
            this.save(demandBugInfo);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    @Override
    public void editDemandBugInfo(DemandBugInfo demandBugInfo) {
        try {
            TableInfoUtil.handleTableVersion(demandBugInfo.getHisVersion()); // 替换表名
            if (!this.checkDemandBugInfoUnique(demandBugInfo)) {
                throw new BusinessException("版本【" + demandBugInfo.getVersion() + "】需求编号【" + demandBugInfo.getDemandBugNum() + "】已存在");
            }
            demandBugInfo.setUpdateTime(new Date());
            demandBugInfo.setUpdateBy(SecurityUtils.getUsername());
            this.updateById(demandBugInfo);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    @Override
    public void deleteDemandBugInfo(DemandBugInfo demandBugInfo) {
        try {
            if (StringUtils.isNull(demandBugInfo) || StringUtils.isEmpty(demandBugInfo.getIdList())) {
                throw new BusinessException("没有获取到要删除的需求BUG信息！");
            }
            TableInfoUtil.handleTableVersion(demandBugInfo.getHisVersion()); // 替换表名
            this.removeByIds(demandBugInfo.getIdList());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 校验编号是否唯一
     *
     * @param demandBugInfo
     * @return 结果
     */
    private boolean checkDemandBugInfoUnique(DemandBugInfo demandBugInfo) {
        String demandBugInfoId = StringUtils.isNull(demandBugInfo.getId()) ? "-1" : demandBugInfo.getId();
        QueryWrapper<DemandBugInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("DEMAND_BUG_NUM", demandBugInfo.getDemandBugNum());
        wrapper.eq("VERSION", demandBugInfo.getVersion());
        DemandBugInfo info = this.getOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getId().equals(demandBugInfoId)) {
            return false;
        }
        return true;
    }


    /**
     * 需求BUG数据的json
     *
     * @return
     * @throws Exception
     */
    public String getDemandBugJsonInfo() {
        // 获取修改记录信息文件 取当前版本号的数据
      /*  String version = dicvalueService.getMaxValue(ReportWorldEnum.REPORT_VERSION.getCode());
        if (StringUtils.isBlank(version)) {
            throw new BusinessException("没有获取到版本号，请稍后重试！");
        }*/
        // 当前版本的需求BUG文件
        QueryWrapper<DemandBugInfo> demandBugInfoQueryWrapper = new QueryWrapper<>();
        // demandBugInfoQueryWrapper.eq("VERSION", version);
        demandBugInfoQueryWrapper.in("STATUS", YssStatusEnum.getUpgradeToolsZipStatus());
        List<DemandBugInfo> demandBugInfoList = this.list(demandBugInfoQueryWrapper);
        String[] includeProperties = {"id", "demandBugNum", "demandBugType", "demandBugDate", "description", "version", "status"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter includefilter = filters.addFilter();
        includefilter.addIncludes(includeProperties);
        return JSONObject.toJSONString(demandBugInfoList, includefilter, SerializerFeature.WriteMapNullValue);
    }


    /**
     * 从项目管理计划文件中读取当前版本的需求
     *
     * @param multipartfile
     * @return
     */
    public String readDemandBugInfo(MultipartFile multipartfile, boolean updateSupport, String hisVersion) {
        StringBuffer buffer = new StringBuffer();
        try {
            if (null == multipartfile) {
                throw new BusinessException("没有获取到文件，请稍后重试！");
            }
            TableInfoUtil.handleTableVersion(hisVersion); // 替换表名
            ExcelReader excelReader = null;
            excelReader = EasyExcel.read(multipartfile.getInputStream()).build();
            EasyExeclUtil.setReadOrder(excelReader);
            ExcelListener<DemandBugInfo> sysUserListener = new ExcelListener<>();
            ReadSheet demandBugInfoExcelSheet = EasyExcel.readSheet(0).
                    head(DemandBugInfo.class).headRowNumber(1).registerReadListener(sysUserListener).build();
            excelReader.read(demandBugInfoExcelSheet);
            List<DemandBugInfo> list = sysUserListener.getDatas();
            if (StringUtils.isEmpty(list)) {
                throw new BusinessException("没有获取到文件的内容，请稍后重试！");
            }
            // 获取现在最大的版本号
            String version = hisVersion;
            if (StringUtils.isEmpty(hisVersion)) {
                List<SysDictData> dictDatas = DictUtils.getDictCache(ReportWorldEnum.REPORT_VERSION.getCode());
                if (StringUtils.isEmpty(dictDatas)) {
                    throw new BusinessException("没有获取到版本号，请稍后重试！");
                }
                version = dictDatas.get(0).getDictValue();
                if (StringUtils.isBlank(version)) {
                    throw new BusinessException("没有获取到版本号，请稍后重试！");
                }
            }
            for (DemandBugInfo demandBugInfo : list) {
                if (StringUtils.isNull(demandBugInfo)) {
                    continue;
                }
                if (null == demandBugInfo.getDemandBugNum()) {
                    throw new BusinessException("没有获取到需求编号，请补充完整！");
                }
                if (StringUtils.isEmpty(demandBugInfo.getDescription())) {
                    throw new BusinessException("没有获取到需求描述信息，请补充完整！");
                }
                if (null == demandBugInfo.getDemandBugDate()) { // 发布日期为空
                    throw new BusinessException("没有获取到需求预计发布日期，请补充完整！");
                }

                // 查询是不是已经存在
                QueryWrapper<DemandBugInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("DEMAND_BUG_NUM", demandBugInfo.getDemandBugNum());
                DemandBugInfo info = this.getOne(wrapper);
                if (null != info && updateSupport) { //按照最新的覆盖
                    this.remove(wrapper);
                } else if (null != info && !updateSupport) {
                    continue;
                }
                demandBugInfo.setId(IdUtils.fastSimpleUUID());
                demandBugInfo.setDemandBugFsource(1);
                if (null != demandBugInfo.getDemandBugFsource() && "内部".equals(demandBugInfo.getDemandBugFsource())) {
                    demandBugInfo.setDemandBugFsource(2);
                }
                demandBugInfo.setCreateBy(SecurityUtils.getUsername());
                demandBugInfo.setCreateTime(new Date());
                demandBugInfo.setStatus(YssStatusEnum.NORMAL.getCode());
                demandBugInfo.setVersion(version);
            }
            if (!StringUtils.isEmpty(list)) {
                this.saveBatch(list);
            }
            buffer.append("成功读取").append("数" + (list.size()) + "条").append("\r\n");
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException(ex.getMessage());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
        return buffer.toString();
    }


}
